#include <iostream>
#include "serial/serial.h"
#include "library.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include "time.h"
#include "TimeStampUtil.hpp"

int main() {
//    std::cout << "Hello, World!" << std::endl;
//    nsMe::DYLIB * dylib=new nsMe::DYLIB();
//    dylib->hello();
//
    std::vector<serial::PortInfo> _serialPortList=  serial::list_ports();

    cout<<_serialPortList.size()<<endl;
    for(int i=0;i<_serialPortList.size();i++){
        cout<<_serialPortList.at(i).port<<endl;
    }

    serial::Serial my_serial("/dev/cu.usbserial-A50285BI", 400000, serial::Timeout::simpleTimeout(1000));
    cout << "Is the serial port open?";
    if(my_serial.isOpen())
        cout << " Yes." << endl;
    else
        cout << " No." << endl;
    char  * buffer=new char ;
    vector<int >_serialData;
    string bufferStr;

    while (true){
        int _availBuf=my_serial.available();
        if(_availBuf>0){
            //my_serial.read(buffer,_availBuf);
            string data=my_serial.read(_availBuf);
            long start=TimeStampUtil::millisecondTimestamp();
            bufferStr.append(data);
            int position=bufferStr.find("helloworld");
            if(position!=-1){
                cout<<position<< endl;

                string serialDataSub=bufferStr.substr(0,position);


                rapidjson::StringBuffer s;
                rapidjson::Writer<rapidjson::StringBuffer >writer(s);
                writer.StartObject();
                writer.Key("data");
                writer.StartArray();
                for (int i = 0; i <serialDataSub.size() ; ++i) {
                    writer.Uint((uint8_t)toascii(serialDataSub.at(i)));
                }
                writer.EndArray();
                writer.EndObject();

                cout<<s.GetString()<<endl;
                long end=TimeStampUtil::millisecondTimestamp();

                cout<<"used time "<<(end-start)<<endl;
                bufferStr.erase(0,position+10);
                cout <<  "remain str length: " <<bufferStr.size()<<endl;
            }


        }


    }


    return 0;
}
